<?php
class UsersController extends appController
{
	var $name = "Users";
	var $components = array("Cookie");
	var $layout = null;
	function beforceFilter(){
		$this->cookie->domain = "www.gushilu.com";
		$this->cookie->time = "30 day";
	}
	function register(){
		if(!(isset($_POST['username']) && strlen($_POST['username']))){
			$msg = "请输入用户名";
			return $this->showMsg($msg);
		}
		if(!(isset($_POST['password']) && strlen($_POST['password']))){
			$msg = "请输入密码";
			return $this->showMsg($msg);
		}
		if(isset($_POST['password']) && strlen($_POST['password'])>10){
			$msg = "密码不能大于10个字符";
			return $this->showMsg($msg);
		}
		if(isset($_POST['username']) && strlen($_POST['username'])>10){
			$msg = "用户名不能大于10个字符";
			return $this->showMsg($msg);
		}
		// if(isset($_POST['email'])&&$_POST['email']){}
		$this->data['User'] = $_POST;
		$autoRender = false;
    	if (!empty($this->data)){
	     	 	$this->data['User']['password'] = md5($this->data['User']['password']);
		        $this->User->create();
		        if($this->User->save($this->data)){
		          	$this->login();
					return;
		        }
	      }
		$this->set('data',json_encode(array('ret'=>100,'msg'=>"请输入完整的注册信息")));
	}
	function showMsg($msg){
		$this->set('data',json_encode(array('ret'=>100,'msg'=>$msg)));
	}
	function login() 
    { 
		if(!(isset($_POST['username']) && strlen($_POST['username']))){
			$msg = "请输入昵称/email";
			return $this->showMsg($msg);
		}
		if(!(isset($_POST['password']) && strlen($_POST['password']))){
			$msg = "请输入密码";
			return $this->showMsg($msg);
		}
		$this->data['User'] = $_POST;
        if(empty($this->data) == false) 
        { 
            if(($user = $this->User->validateLogin($this->data['User'])) == true) 
            { 
                $this->Cookie->write('user', $user);
				$this->set('data',json_encode(array('ret'=>0)));
          		return;
            } 
            else 
            { 
				$msg="昵称/email或者密码不正确，清重新填写";
                $this->showMsg($msg);
            } 
        } 
    } 
    function logout() 
    {
        $this->Cookie->delete('user'); 
        $this->redirect('/blogs/index'); 
    }
}
?>